//
//  ApConfigWifiManager.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/8/24.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "ApConfigWifiManager.h"
#import "GCDAsyncUdpSocket.h"

#define udpPortForApConfig 988

@interface ApConfigWifiManager () <GCDAsyncUdpSocketDelegate>
@property (strong, nonatomic)GCDAsyncUdpSocket * udpSocket;
@property (strong, nonatomic)NSArray *waitToSendMsgList;
@end
@implementation ApConfigWifiManager
+(instancetype)shareAPManage{
    static dispatch_once_t onceToken;
    static ApConfigWifiManager *myAPManage = nil;
    dispatch_once(&onceToken, ^{
        myAPManage = [[ApConfigWifiManager alloc]init];
    });
    return myAPManage;
}

-(void)createClientUdpSocket{
    //创建udp socket
    self.udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
    //banding一个端口(可选),如果不绑定端口,那么就会随机产生一个随机的电脑唯一的端口
    NSError * error = nil;
    [self.udpSocket bindToPort:udpPortForApConfig error:&error];
    
    //启用广播
    [self.udpSocket enableBroadcast:YES error:&error];
    
    if (error) {//监听错误打印错误信息
        NSLog(@"error:%@",error);
    }else {//监听成功则开始接收信息
        [self.udpSocket beginReceiving:&error];
    }
}

//广播
-(void)broadcast:(NSString*)wifiName wifiPwd:(NSString*)wifiPwd suc:(void(^)())suc fail:(void(^)())fail{
    [self createClientUdpSocket];
    self.sucBackBlock = suc;
    self.failBackBlock = fail;
    NSString *wifiNameStr = [NSString stringWithFormat:@"hlkATat+Sssid=%@\r\n",wifiName];
    NSString *wifiPwdStr = [NSString stringWithFormat:@"hlkATat+Spw=%@\r\n",wifiPwd];
    self.waitToSendMsgList = @[@"hlkATat+WA=0\r\n",
                               wifiNameStr,
                               wifiPwdStr,
                               @"hlkATat+SAVE=1\r\n",
                               @"hlkATat+Rb=1\r\n"];
    for (int i=0; i<[self.waitToSendMsgList count]; i++) {
        [self sendIndex:i];
    }
}
-(void)sendIndex:(NSInteger)index{
    NSString *perStr = [self.waitToSendMsgList objectAtIndex:index];
    NSData *data = [perStr dataUsingEncoding:NSUTF8StringEncoding];
    //此处如果写成固定的IP就是对特定的server监测
    NSString *host = @"255.255.255.255";
    
    //发送数据（tag: 消息标记）
    [self.udpSocket sendData:data toHost:host port:udpPortForApConfig withTimeout:-1 tag:1000+index];
}

#pragma mark GCDAsyncUdpSocketDelegate
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address{
    NSLog(@"连接上地址了%@",address);
}
//发送数据成功
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
    NSLog(@"标记为%ld的数据发送完成了",tag);
    if (tag == 1004) {
        self.sucBackBlock();
    }
}

//发送数据失败
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
    NSLog(@"标记为%ld的数据发送失败，失败原因：%@",tag, error);
    self.failBackBlock();
}

//接收到数据
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *addressstr = [[NSString alloc] initWithData:address encoding:NSUTF8StringEncoding];
    NSLog(@"收到服务端的响应返回数据：%@---%@",str,addressstr);
}
//socket通道关闭
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError  * _Nullable)error{
    self.failBackBlock();
}
@end
